<?php

namespace App\Kuafu\Complain\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\User\Model\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ComplainModel extends BaseModel
{
    protected $connection = 'mysql';
    protected $table      = 'feature_complain';
    protected $primaryKey = 'id';
    protected $fillable   = [
        'id',
        'shopId',
        'orderId',
        'userId',
        'problemPid',
        'problemChildId',
        'reason',
        'desc',
        'phone',
        'img',
        'status',
        'remark',
        'completeTime',
        'updatedByUid',
        'createdByUid',
        'updatedAt',
        'createdAt',
    ];

    const STATUS_DEFAULT = 0; //0未处理
    const STATUS_SUC     = 1; //1已完成

    const MAPPING_STATUS = [
        self::STATUS_DEFAULT => '处理中',
        self::STATUS_SUC     => '已完成',
    ];

    public function userRel(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'updatedByUid');
    }

    public function shopRel(): HasOne
    {
        return $this->hasOne(Shop::class, 'id', 'shopId');
    }

    /**
     * 新增投诉
     * @param array $data
     * @return Model
     */
    public static function addComplain(array $data): Model
    {
        return self::query()->create($data);
    }


    /**
     * 根据id查询投诉详情
     * @param $id
     * @return Builder|Model|object|null
     */
    public static function getComplainInfoById($id)
    {
        return self::query()->where(['id' => $id])
            ->select(['id', 'orderId', 'shopId', 'reason', 'status', 'completeTime', 'createdAt', 'updatedByUid', 'desc', 'phone', 'img', 'remark'])
            ->with(['shopRel', 'userRel'])
            ->first();
    }


    /**
     * 修改投诉
     * @param $id
     * @param $data
     * @return int
     */
    public static function setComplainInfoById($id, $data): int
    {
        return self::query()->where(['id' => $id, 'status' => self::STATUS_DEFAULT])->update($data);
    }
}
